package com.ysu.concurrency.thread.blockingqueue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author 郭辉
 * @className PCBlockingQueue
 * @description 基于BlockingQueue实现P-C
 * @date 2022/1/13 15:32
 * @company 海康威视
 */
public class PCBlockingQueue {
    public static void main(String[] args) {
        BlockingQueueSource<Integer> source = new BlockingQueueSource<>();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    source.add(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"P1").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    source.add(i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"P2").start();
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                try {
                    source.min();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();
    }
}

class BlockingQueueSource<T>{
    private BlockingQueue<T> queue = new ArrayBlockingQueue<T>(capacity);
    private static final int capacity = 10;
    public void add(T pam) throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "准备放入元素" + pam.toString());
        queue.put(pam);
        System.out.println(Thread.currentThread().getName() + "放入元素" + pam);
    }
    public void min() throws InterruptedException {
        System.out.println(Thread.currentThread().getName() + "准备取出元素");
        T take = queue.take();
        System.out.println(Thread.currentThread().getName() + "取出元素" + take);
    }
}